<template>
  <div class="detection-record-card">
    <div class="card-header">
        检测记录
    </div>

    <div class="card-content">
      <div class="device-carousel" ref="carousel">
        <div class="carousel-wrapper" :style="{ transform: `translateY(${scrollOffset}px)` }">
          <div v-for="(device, index) in displayDevices"
               :key="`${device.latheName}-${index}`"
               class="device-record-item"
               :class="[
                 getStatusClass(device.status),
                 { 'active-item': currentActiveIndex === index % uniqueLatheNames.length },
                 { 'highlight-item': device.isNewFault }
               ]"
               @click="selectDevice(device)">

            <!-- 设备状态指示器 -->
            <div class="status-indicator" :class="getStatusClass(device.status)">
              <div class="status-dot"></div>
              <div class="status-ring"></div>
            </div>

            <!-- 设备信息 -->
            <div class="device-info">
              <div class="device-name">{{ device.latheName }}</div>
              <div class="device-details">
                <span class="status-text" :class="getStatusClass(device.status)">
                  {{ device.status }}
                </span>
                <span class="update-time">{{ formatTime(device.collectTime) }}</span>
              </div>
            </div>

<!--            &lt;!&ndash; 操作按钮 &ndash;&gt;-->
<!--            <div class="device-actions">-->
<!--              <div v-if="device.status === '故障'"-->
<!--                   class="ai-inquiry-btn"-->
<!--                   @click.stop="inquiryFromDevice(device)">-->
<!--                <i class="el-icon-service"></i>-->
<!--              </div>-->
<!--              <div class="select-btn" @click.stop="selectDevice(device)">-->
<!--                <i class="el-icon-view"></i>-->
<!--              </div>-->
<!--            </div>-->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DetectionRecordCard',
  props: {
    uniqueLatheNames: {
      type: Array,
      default: () => []
    },
    getLatheNameStatus: {
      type: Function,
      required: true
    },
    latheNameSummaries: {
      type: Object,
      default: () => ({})
    },
    currentDevice: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      scrollOffset: 0,
      currentActiveIndex: 0,
      carouselTimer: null,
      itemHeight: 70, // 每个设备记录项的高度
      visibleCount: 5, // 可见的设备记录数量
      carouselInterval: 4000, // 轮播间隔（毫秒）
      newFaultDevices: new Set() // 新故障设备集合
    };
  },
  computed: {
    // 构建设备数据列表
    deviceList() {
      return this.uniqueLatheNames.map(latheName => {
        const status = this.getLatheNameStatus(latheName);
        const summary = this.latheNameSummaries[latheName] || {};

        return {
          latheName,
          status,
          collectTime: summary.collectTime || new Date().toISOString(),
          isNewFault: this.newFaultDevices.has(latheName) && status === '故障'
        };
      });
    },

    // 用于轮播显示的设备列表
    displayDevices() {
      if (!this.deviceList || this.deviceList.length === 0) {
        return [];
      }

      // 如果设备数量少于可见数量，直接返回
      if (this.deviceList.length <= this.visibleCount) {
        return this.deviceList;
      }

      // 创建循环显示的设备列表
      const devices = [...this.deviceList];
      // 在末尾添加前几个项目，实现无缝循环
      const extraDevices = devices.slice(0, this.visibleCount);
      return [...devices, ...extraDevices];
    },

    // 统计各状态设备数量
    statusCounts() {
      const counts = {
        normal: 0,
        error: 0,
        warning: 0,
        offline: 0
      };

      this.deviceList.forEach(device => {
        const statusClass = this.getStatusClass(device.status);
        if (counts.hasOwnProperty(statusClass)) {
          counts[statusClass]++;
        }
      });

      return counts;
    }
  },
  watch: {
    uniqueLatheNames: {
      handler(newNames) {
        if (newNames && newNames.length > 0) {
          this.startCarousel();
        } else {
          this.stopCarousel();
        }
      },
      immediate: true
    },

    // 监听设备状态变化，检测新故障
    deviceList: {
      handler(newList, oldList) {
        if (oldList && oldList.length > 0) {
          this.detectNewFaults(newList, oldList);
        }
      },
      deep: true
    }
  },
  mounted() {
    this.startCarousel();
  },
  beforeDestroy() {
    this.stopCarousel();
  },
  methods: {
    getStatusClass(status) {
      const statusMap = {
        '正常': 'normal',
        '故障': 'error',
        '待机': 'warning',
        '离线': 'offline'
      };
      return statusMap[status] || 'offline';
    },

    formatTime(timestamp) {
      if (!timestamp) return '';

      const date = new Date(timestamp);
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    startCarousel() {
      this.stopCarousel();

      if (!this.deviceList || this.deviceList.length <= this.visibleCount) {
        return;
      }

      this.carouselTimer = setInterval(() => {
        this.scrollToNext();
      }, this.carouselInterval);
    },

    stopCarousel() {
      if (this.carouselTimer) {
        clearInterval(this.carouselTimer);
        this.carouselTimer = null;
      }
    },

    scrollToNext() {
      if (!this.deviceList || this.deviceList.length <= this.visibleCount) {
        return;
      }

      this.currentActiveIndex++;
      const maxIndex = this.deviceList.length;

      // 计算滚动偏移
      this.scrollOffset = -this.currentActiveIndex * this.itemHeight;

      // 如果滚动到末尾，重置到开始位置
      if (this.currentActiveIndex >= maxIndex) {
        setTimeout(() => {
          this.currentActiveIndex = 0;
          this.scrollOffset = 0;
        }, 500); // 等待过渡动画完成
      }
    },

    selectDevice(device) {
      this.$emit('select-device', device.latheName);
    },

    inquiryFromDevice(device) {
      this.$emit('inquiry-from-device', {
        deviceName: device.latheName,
        status: device.status,
        collectTime: device.collectTime
      });
    },

    // 检测新故障设备
    detectNewFaults(newList, oldList) {
      const oldStatusMap = {};
      oldList.forEach(device => {
        oldStatusMap[device.latheName] = device.status;
      });

      newList.forEach(device => {
        const oldStatus = oldStatusMap[device.latheName];
        if (oldStatus && oldStatus !== '故障' && device.status === '故障') {
          this.newFaultDevices.add(device.latheName);

          // 5秒后移除新故障标记
          setTimeout(() => {
            this.newFaultDevices.delete(device.latheName);
          }, 5000);
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
@import './mixins/cardStyles.scss';

.detection-record-card {
  height: 80%;
  @include card-base-style;
  display: flex;
  flex-direction: column;

  .card-header {
    padding: 15px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      @include card-title-style;
      display: flex;
      align-items: center;


      i {
        margin-right: 8px;
        color: #00d4ff;
      }


    .status-summary {
      display: flex;
      gap: 15px;

      .summary-item {
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 4px;
        font-weight: 500;

        &.normal {
          color: #4CAF50;
          background: rgba(76, 175, 80, 0.1);
        }

        &.error {
          color: #FF5722;
          background: rgba(255, 87, 34, 0.1);
        }

        &.warning {
          color: #FF9800;
          background: rgba(255, 152, 0, 0.1);
        }

        &.offline {
          color: #9E9E9E;
          background: rgba(158, 158, 158, 0.1);
        }
      }
    }
  }

  .card-content {
    flex: 1;
    padding: 10px;
    overflow: hidden;

    .device-carousel {
      height: 100%;
      position: relative;
      overflow: hidden;

      .carousel-wrapper {
        transition: transform 0.5s ease-in-out;
        position: relative;
      }


      .device-record-item {
        display: flex;
        align-items: center;
        padding: 12px 15px;
        margin-bottom: 10px;
        background: linear-gradient(135deg, rgba(15, 35, 75, 0.8), rgba(10, 25, 60, 0.6));
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.08);
        transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
        height: 60px;

        position: relative;
        cursor: pointer;
        overflow: hidden;

        // 背景光效
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.03), transparent);
          transition: left 0.8s ease;
        }

        &:hover {
          background: linear-gradient(135deg, rgba(20, 45, 95, 0.9), rgba(15, 35, 75, 0.8));
          transform: translateX(3px) scale(1.02);
          border-color: rgba(255, 255, 255, 0.15);
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);

          &::before {
            left: 100%;
          }
        }

        &.active-item {
          background: linear-gradient(135deg, rgba(0, 212, 255, 0.15), rgba(0, 212, 255, 0.08));
          border-color: rgba(0, 212, 255, 0.3);
          transform: scale(1.03);
        }

        &.highlight-item {
          background: linear-gradient(135deg, rgba(255, 43, 43, 0.2), rgba(255, 43, 43, 0.1));
          border-color: rgba(255, 43, 43, 0.4);
          animation: fault-highlight 2s infinite ease-in-out;
        }

        // 状态指示器
        .status-indicator {
          width: 14px;
          height: 14px;
          margin-right: 12px;
          position: relative;

          .status-dot {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            position: relative;
            z-index: 2;
          }

          .status-ring {
            position: absolute;
            top: -3px;
            left: -3px;
            right: -3px;
            bottom: -3px;
            border-radius: 50%;
            opacity: 0.4;
            animation: status-pulse 2s infinite;
          }

          &.normal {
            .status-dot {
              background: #4CAF50;
              box-shadow: 0 0 8px rgba(76, 175, 80, 0.6);
            }
            .status-ring {
              border: 2px solid #4CAF50;
            }
          }

          &.error {
            .status-dot {
              background: #FF5722;
              box-shadow: 0 0 8px rgba(255, 87, 34, 0.6);
              animation: error-flash 1s infinite;
            }
            .status-ring {
              border: 2px solid #FF5722;
              animation: error-ring 1s infinite;
            }
          }

          &.warning {
            .status-dot {
              background: #FF9800;
              box-shadow: 0 0 8px rgba(255, 152, 0, 0.6);
            }
            .status-ring {
              border: 2px solid #FF9800;
            }
          }

          &.offline {
            .status-dot {
              background: #9E9E9E;
              box-shadow: 0 0 4px rgba(158, 158, 158, 0.4);
            }
            .status-ring {
              border: 2px solid #9E9E9E;
            }
          }
        }

        // 设备信息
        .device-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;

          .device-name {
            color: #ffffff;
            font-size: 15px;
            font-weight: 600;
            margin-bottom: 4px;
            letter-spacing: 0.3px;
          }

          .device-details {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .status-text {
              font-size: 12px;
              font-weight: 500;
              padding: 2px 6px;
              border-radius: 3px;

              &.normal {
                color: #4CAF50;
                background: rgba(76, 175, 80, 0.1);
              }

              &.error {
                color: #FF5722;
                background: rgba(255, 87, 34, 0.1);
              }

              &.warning {
                color: #FF9800;
                background: rgba(255, 152, 0, 0.1);
              }

              &.offline {
                color: #9E9E9E;
                background: rgba(158, 158, 158, 0.1);
              }
            }

            .update-time {
              color: #8f9bb3;
              font-size: 11px;
              font-weight: 400;
            }
          }
        }

        // 操作按钮
        .device-actions {
          display: flex;
          align-items: center;
          gap: 8px;

          .ai-inquiry-btn,
          .select-btn {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);

            i {
              font-size: 12px;
            }

            &:hover {
              transform: scale(1.1);
            }
          }

          .ai-inquiry-btn {
            background: linear-gradient(135deg, rgba(255, 43, 43, 0.3), rgba(255, 43, 43, 0.2));
            color: #ff2b2b;
            border: 1px solid rgba(255, 43, 43, 0.4);
            animation: ai-pulse 1.5s infinite ease-in-out;

            &:hover {
              background: linear-gradient(135deg, rgba(255, 43, 43, 0.5), rgba(255, 43, 43, 0.3));
              box-shadow: 0 4px 12px rgba(255, 43, 43, 0.3);
            }
          }

          .select-btn {
            background: linear-gradient(135deg, rgba(0, 212, 255, 0.3), rgba(0, 212, 255, 0.2));
            color: #00d4ff;
            border: 1px solid rgba(0, 212, 255, 0.4);

            &:hover {
              background: linear-gradient(135deg, rgba(0, 212, 255, 0.5), rgba(0, 212, 255, 0.3));
              box-shadow: 0 4px 12px rgba(0, 212, 255, 0.3);
            }
          }
        }
      }
    }
  }
}

// 动画定义
@keyframes fault-highlight {
  0%, 100% {
    border-color: rgba(255, 43, 43, 0.4);
    box-shadow: 0 0 0 rgba(255, 43, 43, 0.3);
  }
  50% {
    border-color: rgba(255, 43, 43, 0.7);
    box-shadow: 0 0 15px rgba(255, 43, 43, 0.2);
  }
}

@keyframes status-pulse {
  0% {
    transform: scale(1);
    opacity: 0.4;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

@keyframes error-flash {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.7;
  }
}

@keyframes error-ring {
  0% {
    transform: scale(1);
    opacity: 0.4;
  }
  100% {
    transform: scale(1.3);
    opacity: 0;
  }
}

@keyframes ai-pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.05);
  }
}
</style>
